package com.freedom.auth.infrastructure.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.freedom.auth.infrastructure.enums.AuthenticationIdentityEnum;
import com.freedom.common.core.constant.SecurityConstant;
import com.freedom.common.framework.util.RequestUtils;
import com.nimbusds.jose.JWSObject;
import jodd.util.StringPool;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AuthUtil {

    @SneakyThrows
    public static String getGrantType() {
        HttpServletRequest request = RequestUtils.getRequest();
        return request.getParameter(SecurityConstant.GRANT_TYPE_KEY);
    }


    /**
     * 解析JWT获取获取认证身份标识
     *
     * @return
     */
    @SneakyThrows
    public static String getAuthenticationIdentity() {
        HttpServletRequest request = RequestUtils.getRequest();
        String refreshToken = request.getParameter(SecurityConstant.REFRESH_TOKEN_KEY);

        String payload = StrUtil.toString(JWSObject.parse(refreshToken).getPayload());
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        return jsonObject.getStr(SecurityConstant.AUTHENTICATION_IDENTITY_KEY);
    }

    @SneakyThrows
    public static String getAuthClientId() {
        HttpServletRequest request = RequestUtils.getRequest();
        String clientId = request.getParameter(SecurityConstant.CLIENT_ID_KEY);
        if (StringUtils.isBlank(clientId)) {
            String authorization = request.getHeader(SecurityConstant.AUTHORIZATION_KEY);
            if (StrUtil.isNotBlank(authorization) && authorization.startsWith(SecurityConstant.BASIC_PREFIX)) {
                authorization = authorization.replace(SecurityConstant.BASIC_PREFIX, Strings.EMPTY);
                String basicPlainText = new String(Base64.getDecoder().decode(authorization.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
                //client:secret
                clientId = basicPlainText.split(StringPool.COLON)[0];
            }
        }
        return clientId;
    }
}
